/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package trumpet.connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import trumpet.core.User;
import trumpet.gui.Message;

/**
 *
 * @author vsemaphore
 */
public class Server extends Thread {
    
    public static final int SERVER_PORT = 666;
    
    protected static Server _instance;
    
    public static Server getInstance()
    {
        if ( ! (_instance instanceof Server) ) {
            _instance = new Server();
        }
        return _instance;
    }
    
    public ServerSocket serverSocket;
    
    public Server()
    {
        try {
            serverSocket = new ServerSocket(SERVER_PORT);
        } catch (IOException e) {
            System.err.println("Serwer socket error: " + e.getMessage());
        }
    }
    
    public Connection createClientConnection(User user)
    {
        Connection c = null;
        String address = user.getIp();
        try {
            Socket s = new Socket(address, SERVER_PORT);
            c = new Connection(s, user);
        } catch (UnknownHostException ex) {
            System.err.println("Host nie odnaleziony: " + address);
        } catch (IOException ex) {
            System.err.println("Blad polaczenia: " + ex.getMessage());
        }
        
        return c;
    }
    
    public void handle()
    { 
        start();
    }
    
    @Override
    public void run()
    {
        while (true) {
            try {
            Socket s = serverSocket.accept();
            System.out.println("New connection: " + s);
            Connection c = new Connection(s, null);
            c.handle();
        } catch (IOException e) {
            System.err.println("Server IO Exception:  " + e);
        }
      } 
    }
}
